<template>
  <div>
    <el-upload class="avatar-uploader" :http-request="upload" action="#" :show-file-list="false" :before-upload="beforeAvatarUpload">
      <img v-if="src" :src="src" class="avatar">
      <i v-else class="el-icon-plus avatar-uploader-icon" />
      <el-progress v-show="isShow" type="line" :percentage="percent" class="progress" />
    </el-upload>
  </div>
</template>

<script>
// 导入cos的SDK调用
import COS from 'cos-js-sdk-v5'
const cos = new COS({
  SecretId: 'AKIDGK9i13pKYVDhuqVu1rQijTw83h4AzXon', // 身份识别ID
  SecretKey: 'lFSN2PVKIzPYQ1LN8cplPmshFWWFgqkM' // 身份秘钥
})

export default {
  name: 'UploadImg',
  props: {
    // 员工头像地址
    src: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      isShow: false,
      percent: 0
      // imageUrl: ''
    }
  },
  methods: {
    upload ({ file }) {
      this.isShow = true

      cos.putObject({
        Bucket: 'hxnphone-1308960448', /* 填入您自己的存储桶，必须字段 */
        Region: 'ap-beijing', /* 存储桶所在地域，例如ap-beijing，必须字段 */
        Key: file.name, /* 存储在桶里的对象键（例如1.jpg，a/b/test.txt），必须字段 */
        StorageClass: 'STANDARD',
        Body: file, // 上传文件对象
        onProgress: (progressData) => {
          this.percent = progressData.percent * 100
        }
      }, (err, data) => {
        // console.log(err || data)
        if (!err) {
          // console.log(data)
          setTimeout(() => {
            // this.imageUrl = `https://${data.Location}`
            // this.$parent.src = `https://${data.Location}`
            this.$emit('update:src', `https://${data.Location}`)
            this.isShow = false
          }, 600)
        }
      })
    },
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    }
  }
}
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
